/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.techshop.dao.impl;

import com.techshop.dao.NewsDao;
import com.techshop.model.News;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Order;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 *
 * @author hai
 */
public class NewsDaoImpl extends HibernateDaoSupport implements NewsDao{

    @Override
    public News getById(int newsId) {
         try
        {
            return (News)getSession().get(News.class, newsId);
        }
        catch (DataAccessResourceFailureException e)
        {
            System.err.printf("Error: ", e.toString());
            return null;
        }
    }

    @Override
    public List<News> findAll() {
       try
        {
//            System.out.println("NNNNNNNNNN----------NNNNNNNNNNNNNNNNNN");
//            Query q = getSession().createQuery("from News");
            Criteria criteria = getSession().createCriteria(News.class);
            criteria.addOrder(Order.desc("id"));
            criteria.setFirstResult(0);
	    criteria.setMaxResults(100);
            return criteria.list();
//            return q.list();
           // return getSession().createQuery("from Comment").list();
        }
        catch (DataAccessResourceFailureException e)
        {
            System.err.printf("Error: ", e.toString());
            return null;
        }
    }

    @Override
    public boolean insert(News news) {
         try
        {
            getHibernateTemplate().save(news);
            return true;
        }
        catch (DataAccessResourceFailureException e)
        {
            System.err.printf("Error: ", e.toString());
            return false;
        }
    }

    @Override
    public boolean update(News news) {
         try
        {
            
                getHibernateTemplate().update(getHibernateTemplate().merge(news));
                return true;
           
        }
        catch (DataAccessResourceFailureException e)
        {
            System.err.printf("Error: ", e.toString());
            return false;
        }
    }

    @Override
    public boolean delete(News news) {
      try
        {
            if (getById(news.getId()) == null)
            {
                return false;
            }
            else
            {
                getHibernateTemplate().delete(getHibernateTemplate().merge(news));
                return true;
            }
        }
        catch (DataAccessResourceFailureException e)
        {
            System.err.printf("Error: ", e.toString());
            return false;
        }
    }
    
    
}
